package problem37;

//37.解数独
//https://leetcode.cn/problems/sudoku-solver/description/
class Solution2 {
    boolean[][] row = new boolean[10][10];
    boolean[][] col = new boolean[10][10];
    boolean[][][] grid = new boolean[3][3][10];
    public void solveSudoku(char[][] board) {
        for(int i = 0; i<9; i++) {
            for(int j = 0; j<9; j++) {
                if(board[i][j] != '.') {
                    int x = board[i][j] - '0';
                    row[i][x] = col[j][x] = grid[i/3][j/3][x] = true;
                }
            }
        }
        dfs(board);
    }
    public boolean dfs(char[][] board) {
        for(int i = 0; i<9; i++) {
            for(int j = 0; j<9; j++) {
                if(board[i][j] == '.') {
                    for (int x = 1; x <= 9; x++) {
                        if(!row[i][x] && !col[j][x] && !grid[i/3][j/3][x]) {
                            row[i][x] = col[j][x] = grid[i/3][j/3][x] = true;
                            board[i][j] = (char)(x + '0');
                            if(dfs(board)) return true;
                            row[i][x] = col[j][x] = grid[i/3][j/3][x] = false;
                            board[i][j] = '.';
                        }
                    }
                    return false;
                }
            }
        }
        return true;
    }
}